package top.shiyiri.java;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Aunean
 * @date 2022/1/10
 */
/*
实现TCP的网络编程
例题二：客户端发送文件给服务端，服务端将文件保存在本地
 */
public class TCPTest2 {

    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        BufferedInputStream bis = null;
        try {
            socket = new Socket(InetAddress.getByName("localhost"), 9000);
            os = socket.getOutputStream();

            bis = new BufferedInputStream(new FileInputStream("../data/photo/q.png"));

            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert bis != null;
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    @Test
    public void server() {

        ServerSocket socket = null;
        Socket accept = null;
        InputStream is = null;
        BufferedOutputStream bos = null;
        try {
            socket = new ServerSocket(9000);
            accept = socket.accept();

            is = accept.getInputStream();

            bos = new BufferedOutputStream(new FileOutputStream("photo1.png"));

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert bos != null;
                bos.close();
                is.close();
                accept.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
